﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using MvcEngine.Core.Website;
using MvcEngine.Core;
using MvcEngine.Core.Extensions;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Account;
using MvcEngine.Core.Localization;
using MvcEngine.Mvc.Models;

namespace MvcEngine.Mvc.ModelBinders
{
    public class AccountModelBinder : ModelBinderBase
    {
        public override object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            AccountViewModel model = new AccountViewModel();
            model.Email = request.Form.Get("Email");
            model.Password = request.Form.Get("Password");
            model.ConfirmationPassword = request.Form.Get("ConfirmationPassword");
            model.FirstName = request.Form.Get("FirstName");
            model.LastName = request.Form.Get("LastName");

            if (string.IsNullOrEmpty(request.Form.Get("Male")))
                bindingContext.ModelState.AddModelError("Male", ResourceReader.Current.GetString("GenderRequiredValidator"));
            else
                model.Male = request.Form.Get("Male").Contains("Male");

            try
            {
                int day = request.Form.Get("Birthday.Day").ToInt();
                int month = request.Form.Get("Birthday.Month").ToInt();
                int year = request.Form.Get("Birthday.Year").ToInt();
                DateTime birthDay = new DateTime(year, month, day);
                model.Birthday = birthDay;
            }
            catch
            {
                bindingContext.ModelState.AddModelError("Birthday.Day", ResourceReader.Current.GetString("IncorrectBirthday"));
            }

            if (model.Password != model.ConfirmationPassword)
                bindingContext.ModelState.AddModelError("ConfirmationPassword", ResourceReader.Current.GetString("ConfirmPasswordIsDifferent"));

            Validate(model, controllerContext);
            return model;
        }
    }
}
